Skip to content

fix: unify answer reliability across all prompts#634

Merged
BigSimmo merged 9 commits into
mainfrom
codex/global-answer-reliability
Jul 13, 2026
Merged

fix: unify answer reliability across all prompts#634
BigSimmo merged 9 commits into
mainfrom
codex/global-answer-reliability

Conversation

@BigSimmo

@BigSimmo BigSimmo commented Jul 13, 2026

Copy link
Copy Markdown
Owner

Summary

  • Apply one governed answer-response contract to every generated answer path: JSON, streaming, demo, document questions, and legacy document summaries.
  • Preserve source-backed fail-closed refusals, feedback-token binding to the answer actually delivered, detailed progress/stop behavior, and the stricter document-summary quota across answer surfaces.
  • Apply relevance-first Australian and Western Australian source preference globally while retaining stronger supplementary evidence inside routine fast budgets and stricter numeric/high-risk safeguards.
  • Preserve up to 40 ordered chunks from a document's committed index generation for full-document summaries, including empty-composer streamed summaries.
  • Add auth-epoch and provider-request cancellation for private document streams plus non-lithium, demo-refusal, summary, route/contract, and Chromium regressions.

Why

A provider or quality-gate failure could leave users with source snippets but no finalized answer, and some secondary answer paths bypassed the same governance, progress, and fallback behavior as the main answer flow. The implementation now applies the same conservative client-response contract to all prompts and answer surfaces without reducing full-document summary coverage, rendering stale authenticated streams, or leaving stopped provider work running.

Areas touched

  • Answer JSON and SSE routes
  • Legacy document-summary route and document viewer
  • Answer contract, source governance, context selection, and RAG orchestration
  • Progress UI, shared stream parsing, auth-epoch cancellation, and provider abort propagation
  • Unit, route, summary, and focused Chromium regressions
  • Branch review ledger

Verification

  • npm run verify:pr-local on merged head b411329ec immediately before the final context-budget fix
    • Node/npm runtime, Prettier, ESLint, typecheck, production build, 652 static pages, and client-bundle secret scan passed.
    • Unit result: 2,240 passed, 1 skipped.
    • Offline RAG result: 21 files and 277 tests passed; 36/36 golden retrieval schema cases loaded.
  • Final head eb6160a14 offline gates
    • npm run verify:cheap: 2,242 passed, 1 skipped; runtime, action/config checks, lint, and typecheck passed.
    • npm run eval:rag:offline: 21 files and 277 tests passed; 36/36 golden retrieval schema cases loaded.
    • npm run check:production-readiness:ci: READY with five expected missing-provider/local-env warnings.
  • Focused Chromium document-answer regression
    • 1/1 passed, covering typed document questions and empty-composer full-document summaryMode with progress.
  • Hosted final-head checks
    • All 14 required/applicable checks passed, including build, unit coverage, static checks, migration replay, critical smoke, full UI regression, Semgrep, Gitleaks, and GitGuardian.
  • npm run verify:ui local aggregate
    • The earlier aggregate local run exceeded the 20-minute limit. Its two isolated timing cases passed after investigation, the affected Chromium cases passed, and hosted UI regression is the merge gate.
  • npm run verify:release
    • Not run because it includes broader provider/release-sensitive gates; hosted PR checks are the handoff boundary.
  • npm run eval:retrieval:quality
    • Not run because it requires live Supabase/OpenAI credentials. No provider API calls were made.
  • npm run eval:rag -- --limit 15 + npm run eval:quality -- --rag-only
    • Not run because these require live provider access. The code-backed offline RAG evaluation passed in verify:pr-local.
  • npm run check:production-readiness
    • npm run check:production-readiness:ci reported READY with provider variables intentionally absent; two local checks passed and five missing-environment warnings were expected.
  • npm run check:deployment-readiness
    • Not applicable: no deployment startup or hosting behavior changed.

Clinical Governance Preflight

  • Source-backed claims still require linked source verification before clinical use
  • No patient-identifiable document workflow was introduced or expanded without explicit governance approval
  • Supabase target remains Clinical KB Database (sjrfecxgysukkwxsowpy)
  • Service-role keys and private document access remain server-only
  • Demo/synthetic content remains clearly separated from real clinical sources
  • Source metadata, review status, and outdated/unknown-source behavior remain conservative
  • Deployment classification/TGA SaMD impact was checked: this changes reliability, fallback, progress, and source ordering without expanding intended clinical use; existing verification warnings and conservative refusals remain.

Review follow-up

  • Fixed full-document context, demo double-governance, private auth-epoch cancellation, feedback-token answer integrity, blank-summary routing, stopped-summary provider cancellation, the streamed-summary quota bypass, and fast-budget supplementary-evidence displacement.
  • Dispositioned the duplicate-test-declaration report after confirming only one declaration and passing TypeScript/full tests; CodeRabbit later withdrew it.
  • Replied to every thread with the repository resolution marker and closed all nine threads.
  • Merged current origin/main (ac48de23b) into the feature branch without force-pushing; the only conflict was append-only review-ledger rows, and both sides were retained.

Risks and rollback

  • Live output quality still depends on publisher/jurisdiction metadata and provider timing; provider-backed quality evaluations remain outstanding by design.
  • The full aggregate local UI suite did not complete, although affected Chromium cases and the hosted full UI regression passed on the final head.
  • Rollback is a normal revert of the eventual squash merge; there are no feature migrations, environment changes, or production-data operations.

Summary by CodeRabbit

  • New Features

    • Added streaming “Answer from this document” generation with progress updates and cancellation.
    • Introduced summaryMode for /api/answer streaming, requiring a document ID and using committed-document summarization.
  • Bug Fixes

    • Centralized governed response shaping for standard, streaming, and demo modes, improving safety-oriented refusals.
    • Added stricter quota enforcement for document-summary streaming to prevent unnecessary generation work.
    • Fail-closed handling for incomplete/invalid answer streams and stronger feedback-token binding on refusals.
  • Documentation

    • Updated release-readiness and verification records in the review ledger.

BigSimmo added 2 commits July 14, 2026 05:26
Route every answer surface through shared governance, Australian-source selection, streaming progress, and document-scoped fallback behavior. Add cross-surface and non-lithium regressions.
@supabase

supabase Bot commented Jul 13, 2026

Copy link
Copy Markdown

This pull request has been ignored for the connected project sjrfecxgysukkwxsowpy because there are no changes detected in supabase directory. You can change this behaviour in Project Integrations Settings ↗︎.


Preview Branches by Supabase.
Learn more about Supabase Branching ↗︎.

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

The changes centralize governed answer payload construction, share SSE parsing across answer surfaces, stream document answers with progress and cancellation, scope document summarization to committed content, and adjust context selection to retain supplementary evidence under explicit limits.

Changes

Governed answer responses

Layer / File(s) Summary
Governed response contract
src/lib/answer-response.ts, tests/answer-response.test.ts
Shared builders derive degraded mode, governance warnings, refusal payloads, telemetry, and demo fallback fields.
Endpoint governance wiring
src/app/api/answer/..., src/app/api/documents/[id]/summarize/route.ts, tests/private-access-routes.test.ts, docs/branch-review-ledger.md
Answer endpoints and document summaries return governed payloads, telemetry, interaction identifiers, feedback metadata, and dedicated document-summary quota handling.

Shared answer streaming

Layer / File(s) Summary
Shared SSE reader
src/components/clinical-dashboard/search-utils.ts, src/components/ClinicalDashboard.tsx, tests/answer-progress.test.ts
SSE parsing and final-payload validation move into readAnswerStream, with progress, token, revision, activity, and retryable-error handling.
Document viewer streaming workflow
src/components/DocumentViewer.tsx, tests/ui-smoke.spec.ts
Document answers use /api/answer/stream, display progress, support cancellation, and avoid the legacy summarize endpoint.

RAG summarization and context selection

Layer / File(s) Summary
Document summary pipeline
src/lib/answer-contract.ts, src/lib/rag.ts, tests/rag-document-summary.test.ts
The document-summary prompt is updated, owner scoping is explicit, and committed chunks are limited and tested.
Context selection policy
src/lib/australian-source-priority.ts, src/lib/rag-context-selection.ts, tests/rag-context-budget.test.ts
Context selection supports configurable supplementary-padding retention and enforces per-document caps while preserving tested ordering behavior.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant DocumentViewer
  participant AnswerStreamAPI
  participant readAnswerStream
  participant AnswerProgressStepper
  DocumentViewer->>AnswerStreamAPI: POST document question
  AnswerStreamAPI-->>readAnswerStream: progress and token SSE events
  readAnswerStream->>AnswerProgressStepper: emit progress updates
  AnswerStreamAPI-->>readAnswerStream: final answer payload
  readAnswerStream-->>DocumentViewer: completed AnswerPayload
Loading

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.58% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title is concise and accurately summarizes the main change: unifying answer reliability across prompts.
Description check ✅ Passed Summary, Verification, and Clinical Governance Preflight are present; only the template's Notes section is missing.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/global-answer-reliability

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cd31912253

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/lib/rag.ts Outdated
@BigSimmo

Copy link
Copy Markdown
Owner Author

@codex resolve actionable Codex review findings for this pull request and current head using the repository instructions. This is the pull request's single automatic repair pass: do not perform a fresh review, create new standalone findings, or request another review. Work only the existing unresolved Codex threads on the current head. Always fix P0 and P1 findings. For P2 and lower findings, fix only clear, scoped, low-risk issues; otherwise disposition them with a concise reason. After fixing or dispositioning a thread, reply in that thread with as the first line, followed by a concise summary; that marker authorizes the workflow to close that exact thread. If human input or new authorization is required, do not use the marker and leave the thread open with the blocker. Finish only after every actionable thread is fixed or dispositioned and closed, or explicitly left open for a human decision. Do not update the branch from main, address unrelated reviews, broaden scope, or create more than one scoped fix commit. Do not use external APIs, paid services, credentials, dependency changes, or broad refactors unless explicitly authorized. Add targeted tests where behavior changes and run the narrowest relevant validation.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/app/api/answer/stream/route.ts`:
- Line 217: Update the demo streaming flow around buildDemoStreamAnswer and
buildGovernedAnswerClientResponse so the already-governed demo client payload is
not governed again; send that existing payload directly, or govern the raw demo
answer only once before response construction. Preserve refusal warnings in the
final SSE payload, and add the smallest targeted stream-level regression test
covering a demo refusal.

In `@src/components/DocumentViewer.tsx`:
- Around line 2461-2462: Update the summary delivery flow in readAnswerStream so
the governed payload’s answer remains exactly equal to payload.answer when
passed to setSummary; remove the client-side cleanClinicalSummaryText
transformation, or ensure sanitization occurs before the server constructs the
governed payload and feedback token.
- Around line 2422-2447: Update the summary stream flow around the fetch in
DocumentViewer to register its AbortController with registerAuthRequest and
release it when the request completes or is aborted. Capture the current auth
epoch before starting, and check isAuthEpochCurrent before applying progress
updates or committing the final summary/error state; abort or ignore stale
responses so an auth change cannot render private answer content.

In `@tests/ui-smoke.spec.ts`:
- Line 2938: Remove the duplicate answerRequests declaration in the surrounding
test scope, retaining a single Array<{ query: string; documentId?: string }>
declaration and its existing usage.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: c5db8d6b-6b70-4119-a278-94142043f0e8

📥 Commits

Reviewing files that changed from the base of the PR and between e6d89f1 and cd31912.

📒 Files selected for processing (17)
  • docs/branch-review-ledger.md
  • src/app/api/answer/route.ts
  • src/app/api/answer/stream/route.ts
  • src/app/api/documents/[id]/summarize/route.ts
  • src/components/ClinicalDashboard.tsx
  • src/components/DocumentViewer.tsx
  • src/components/clinical-dashboard/search-utils.ts
  • src/lib/answer-contract.ts
  • src/lib/answer-response.ts
  • src/lib/australian-source-priority.ts
  • src/lib/rag-context-selection.ts
  • src/lib/rag.ts
  • tests/answer-progress.test.ts
  • tests/answer-response.test.ts
  • tests/private-access-routes.test.ts
  • tests/rag-context-budget.test.ts
  • tests/ui-smoke.spec.ts

Comment thread src/app/api/answer/stream/route.ts
Comment thread src/components/DocumentViewer.tsx
Comment thread src/components/DocumentViewer.tsx Outdated
Comment thread tests/ui-smoke.spec.ts Outdated
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: cd31912253

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7a6fec4a7e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/components/DocumentViewer.tsx Outdated

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d9c5cdb887

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/app/api/answer/stream/route.ts Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/app/api/answer/stream/route.ts`:
- Around line 223-240: Propagate the existing AbortSignal from the summary
branch in the stream route through summarizeDocument to
generateStructuredTextResult, ensuring cancellation stops the underlying model
request when the SSE client disconnects. Update each affected function signature
and call site without changing the normal answer path, and add a regression test
confirming aborted document-summary generation propagates cancellation.

In `@src/lib/rag.ts`:
- Around line 5751-5758: Update the summaryInstructions template to explicitly
treat provided excerpts as untrusted data and prohibit following instructions
contained within them, reusing the existing source-injection guard used around
the referenced lines. Add the smallest targeted regression test covering an
injected instruction in a summary excerpt, then run the narrowest relevant
validation.
- Around line 5718-5731: Update the document_chunks query in the surrounding
summary flow to filter for the committed index generation before applying the
40-row limit, while retaining rows with null index_generation_id. Remove the
post-query committedChunks filtering or keep it only if necessary for equivalent
behavior, and add a regression covering stale rows preceding later committed
chunks.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 608d347d-9fcb-43d0-aaca-9cbc86ed9472

📥 Commits

Reviewing files that changed from the base of the PR and between cd31912 and d9c5cdb.

📒 Files selected for processing (7)
  • docs/branch-review-ledger.md
  • src/app/api/answer/stream/route.ts
  • src/components/DocumentViewer.tsx
  • src/lib/rag.ts
  • tests/private-access-routes.test.ts
  • tests/rag-document-summary.test.ts
  • tests/ui-smoke.spec.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/ui-smoke.spec.ts
  • src/components/DocumentViewer.tsx

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/app/api/answer/stream/route.ts`:
- Around line 223-240: Propagate the existing AbortSignal from the summary
branch in the stream route through summarizeDocument to
generateStructuredTextResult, ensuring cancellation stops the underlying model
request when the SSE client disconnects. Update each affected function signature
and call site without changing the normal answer path, and add a regression test
confirming aborted document-summary generation propagates cancellation.

In `@src/lib/rag.ts`:
- Around line 5751-5758: Update the summaryInstructions template to explicitly
treat provided excerpts as untrusted data and prohibit following instructions
contained within them, reusing the existing source-injection guard used around
the referenced lines. Add the smallest targeted regression test covering an
injected instruction in a summary excerpt, then run the narrowest relevant
validation.
- Around line 5718-5731: Update the document_chunks query in the surrounding
summary flow to filter for the committed index generation before applying the
40-row limit, while retaining rows with null index_generation_id. Remove the
post-query committedChunks filtering or keep it only if necessary for equivalent
behavior, and add a regression covering stale rows preceding later committed
chunks.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 608d347d-9fcb-43d0-aaca-9cbc86ed9472

📥 Commits

Reviewing files that changed from the base of the PR and between cd31912 and d9c5cdb.

📒 Files selected for processing (7)
  • docs/branch-review-ledger.md
  • src/app/api/answer/stream/route.ts
  • src/components/DocumentViewer.tsx
  • src/lib/rag.ts
  • tests/private-access-routes.test.ts
  • tests/rag-document-summary.test.ts
  • tests/ui-smoke.spec.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/ui-smoke.spec.ts
  • src/components/DocumentViewer.tsx
🛑 Comments failed to post (3)
src/app/api/answer/stream/route.ts (1)

223-240: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Propagate cancellation into document-summary generation.

The normal answer path forwards signal, but the summary path drops it at Line 225. Stopping a streamed summary therefore leaves its model request running after the SSE client disconnects. Thread AbortSignal through summarizeDocument into generateStructuredTextResult, and add an abort regression.

As per coding guidelines, “For bug hunts, trace invalid input, empty states, retries, races, stale state, network/auth failures, permissions, and boundary values.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/app/api/answer/stream/route.ts` around lines 223 - 240, Propagate the
existing AbortSignal from the summary branch in the stream route through
summarizeDocument to generateStructuredTextResult, ensuring cancellation stops
the underlying model request when the SSE client disconnects. Update each
affected function signature and call site without changing the normal answer
path, and add a regression test confirming aborted document-summary generation
propagates cancellation.

Source: Coding guidelines

src/lib/rag.ts (2)

5718-5731: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Show the relevant section with line numbers
sed -n '5685,5755p' src/lib/rag.ts | cat -n

# Search for summarizeDocument-related tests and committed generation handling
rg -n "summarizeDocument|committedIndexGeneration|index_generation_id|document_chunks" src test tests __tests__ -g '!node_modules'

Repository: BigSimmo/Database

Length of output: 39215


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Narrow search for tests touching the summary pipeline
rg -n "summarizeDocument|committedIndexGeneration|index_generation_id" src test tests __tests__ -g '*.{ts,tsx,js,jsx}'

# Inspect the current function slice if needed
sed -n '5685,5755p' src/lib/rag.ts | cat -n

Repository: BigSimmo/Database

Length of output: 18544


Filter committed chunks before the 40-row cap. Limiting first and then discarding stale generations can drop later committed sections from the summary. Keep legacy index_generation_id-less rows, but push the committed-generation predicate into the query so the limit applies only to eligible chunks; add a regression for stale rows ahead of later committed chunks.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/lib/rag.ts` around lines 5718 - 5731, Update the document_chunks query in
the surrounding summary flow to filter for the committed index generation before
applying the 40-row limit, while retaining rows with null index_generation_id.
Remove the post-query committedChunks filtering or keep it only if necessary for
equivalent behavior, and add a regression covering stale rows preceding later
committed chunks.

Source: Coding guidelines


5751-5758: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Apply the untrusted-source boundary to summaries.

The regular answer prompt explicitly treats excerpts as untrusted data, but this summary prompt does not. An uploaded chunk can inject instructions that steer a clinically unsafe summary while still citing valid chunk IDs. Reuse the source-injection guard from Lines 4745-4749 and add a prompt-contract regression.

As per coding guidelines, “When behavior changes, add or update the smallest relevant targeted test and run the narrowest relevant validation before broader suites.”

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/lib/rag.ts` around lines 5751 - 5758, Update the summaryInstructions
template to explicitly treat provided excerpts as untrusted data and prohibit
following instructions contained within them, reusing the existing
source-injection guard used around the referenced lines. Add the smallest
targeted regression test covering an injected instruction in a summary excerpt,
then run the narrowest relevant validation.

Source: Coding guidelines

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 588c34c3d4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/app/api/answer/stream/route.ts

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e6791125ac

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/lib/rag-context-selection.ts Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/app/api/answer/stream/route.ts (1)

247-252: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Summary telemetry query field diverges from the non-streaming summarize route.

Here logAnswerDiagnostics logs body.query unconditionally, including for summaryMode requests. The sibling documents/[id]/summarize/route.ts logs a fixed documentSummaryQuestion constant for the same logical "document summary" operation instead of the caller-supplied text. This makes diagnostics for functionally identical summary requests inconsistent depending on which route served them, which cuts against this PR's goal of unifying the answer contract across surfaces. Consider using the same canonical label for summaryMode requests here.

♻️ Proposed fix
-          logAnswerDiagnostics({
-            supabase: createAdminClient(),
-            query: body.query,
-            ownerId,
-            answer: governedResponse.telemetryAnswer,
-          });
+          logAnswerDiagnostics({
+            supabase: createAdminClient(),
+            query: body.summaryMode ? documentSummaryQuestion : body.query,
+            ownerId,
+            answer: governedResponse.telemetryAnswer,
+          });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/app/api/answer/stream/route.ts` around lines 247 - 252, Update the
logAnswerDiagnostics call in the streaming answer route to use the canonical
documentSummaryQuestion label when summaryMode is enabled, matching the
non-streaming summarize route; continue logging body.query for non-summary
requests.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/app/api/answer/stream/route.ts`:
- Around line 247-252: Update the logAnswerDiagnostics call in the streaming
answer route to use the canonical documentSummaryQuestion label when summaryMode
is enabled, matching the non-streaming summarize route; continue logging
body.query for non-summary requests.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 6b3b5151-0589-4d5a-9683-b30b1a088629

📥 Commits

Reviewing files that changed from the base of the PR and between 588c34c and e679112.

📒 Files selected for processing (3)
  • docs/branch-review-ledger.md
  • src/app/api/answer/stream/route.ts
  • tests/private-access-routes.test.ts

@BigSimmo
BigSimmo merged commit d05eae2 into main Jul 13, 2026
20 checks passed
@BigSimmo
BigSimmo deleted the codex/global-answer-reliability branch July 14, 2026 11:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant